package com.lvcoding.auth2.auth.shizhan.security;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * 授权异常类
 * 通常是服务已经识别了请求，已经认证过了，但是对请求的资源没有权限，触发此异常
 * 返回403
 *
 * @author wuyanshen
 */
@Component
public class CustomAccessDeniedHandler implements AccessDeniedHandler {

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        ObjectMapper objectMapper = new ObjectMapper();
        Map<String, Object> map = new HashMap<>();
        map.put("code", 403);
        map.put("msg", accessDeniedException.getMessage());
        String jsonStr = objectMapper.writeValueAsString(map);
        response.setContentType("application/json");
        PrintWriter writer = response.getWriter();
        writer.write(jsonStr);
        writer.flush();
        writer.close();
    }
}
